package com.Iconcat.system.controller;

import com.Iconcat.system.entity.CatUser;
import com.Iconcat.system.entity.PaymentMethod;
import com.Iconcat.system.entity.RechargeRecord;
import com.Iconcat.system.entity.UserPaymentMethod;
import com.Iconcat.system.response.Result;
import com.Iconcat.system.service.CatUserService;
import com.Iconcat.system.service.PaymentMethodService;
import com.Iconcat.system.service.RechargeRecordService;
import com.Iconcat.system.service.UserPaymentMethodService;
import com.Iconcat.system.util.DateTimeParser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/recharge")
@CrossOrigin
@Api(value = "充值模块", tags = "充值记录接口")
public class RechargeController {
    @Resource
    private RechargeRecordService rechargeRecordService;

    @Resource
    private PaymentMethodService paymentMethodService;

    @Resource
    private UserPaymentMethodService userPaymentMethodService;
    @Resource
    private CatUserService catUserService;

    @GetMapping("/getRechCord")
    public Result getOrderListPage(
            @RequestParam(required = true, defaultValue = "1") Integer current,
            @RequestParam(required = true, defaultValue = "10") Integer size,
            @RequestParam(required = false) String searchCreateTime,
            @RequestParam(required = false) String searchStatus,
            @RequestParam(required = false) String searchRecordNumber) throws ParseException {
        // 创建分页对象
        Page<RechargeRecord> page = new Page<>(current, size);
        // 构建查询条件
        LambdaQueryWrapper<RechargeRecord> queryWrapper = new LambdaQueryWrapper<>();
        // 添加条件：如果 searchCreateTime 不为空，则添加按照创建时间范围查询
        if (StringUtils.isNotBlank(searchCreateTime)) {
            queryWrapper.eq(RechargeRecord::getRechargeTime, DateTimeParser.parseTime(searchCreateTime));
        }

        // 添加条件：如果 searchStatus 不为空，则添加按照状态查询
        if (StringUtils.isNotBlank(searchStatus)) {
            queryWrapper.eq(RechargeRecord::getStatus, searchStatus);
        }

        // 添加条件：如果 searchRecordId 不为空，则添加按照记录ID查询
        if (StringUtils.isNotBlank(searchRecordNumber)) {
            queryWrapper.like(RechargeRecord::getOrderNumber, searchRecordNumber);
        }

        // 执行分页查询
        IPage<Map<String, Object>> result = rechargeRecordService.getOrderListPage(page, queryWrapper);

        return Result.ok().data("list", result);
    }

    // 用户发起充值请求
    @PostMapping("/initiate")
    public Result initiateRecharge(@RequestBody RechargeRecord rechargeRecord) throws IOException {

        try {// 生成订单号
            String orderNumber = generateOrderNumber(rechargeRecord.getUserid());

            // 直接设置为已支付
            rechargeRecord.setStatus("未支付");
            rechargeRecord.setOrderNumber(orderNumber);
            BigDecimal amount = rechargeRecord.getAmount();
            System.out.println("amount"+amount);
//            BigDecimal amountBigDecimal = BigDecimal.valueOf(amount);
            rechargeRecord.setAmount(amount);
            rechargeRecordService.save(rechargeRecord);

            // 更新用户余额
            CatUser user = catUserService.getById(rechargeRecord.getUserid());
            user.setAvailableBalance(user.getAvailableBalance().add(rechargeRecord.getAmount()));
            user.setWithdrawableBalance(user.getWithdrawableBalance().add(rechargeRecord.getAmount()));
            user.setTotalAssets(user.getTotalAssets().add(rechargeRecord.getAmount()));
            user.setTotalRecharge(user.getTotalRecharge().add(rechargeRecord.getAmount()));
            catUserService.updateById(user);

            return Result.ok().message("申请成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("申请失败");
        }
    }

    @PostMapping("/detetrecord")
    public Result deleteByid(@RequestBody RechargeRecord rechargeRecord) {
        try {
            rechargeRecordService.removeById(rechargeRecord.getRecordId());
            return Result.ok().message("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("删除失败");
        }
    }

    //后台确认支付
    @PostMapping("/confirmPayment")
    public Result confirmPayment(@RequestBody RechargeRecord rechargeRecord) {
        try {
//            long recordId= rechargeRecord.getUserid();
//            long userid=rechargeRecord.getUserid();
//            String status=rechargeRecord.getStatus();
            rechargeRecord.setStatus("已支付");
            rechargeRecordService.updateRecordId(rechargeRecord);

            // You may want to perform additional logic here if needed

            return Result.ok().message("支付确认成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error().message("支付确认失败");
        }
    }

    // 生成订单号的方法
    private String generateOrderNumber(Long userId) {
        // 获取当前时间
        Date now = new Date();
        // 格式化时间为字符串，可以根据需要调整格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dateString = dateFormat.format(now);

        // 拼接订单号前缀
        String orderNumberPrefix = "ORDER";

        // 生成唯一标识，这里简化为取当前时间的毫秒数
        long uniqueIdentifier = System.currentTimeMillis();

        // 拼接订单号
        return orderNumberPrefix + dateString + userId + uniqueIdentifier;
    }
//    private boolean performPaymentLogic(RechargeRecord rechargeRecord) {
//        // 模拟支付接口调用
//        // 这里可以根据实际情况调用支付宝、微信支付等接口
//
//        // 模拟支付成功的条件
//        boolean paymentSuccess = Math.random() > 0.2; // 80% 的概率支付成功
//
//        if (paymentSuccess) {
//            // 在实际应用中，可能还需要更新支付状态、记录支付流水号等操作
//            System.out.println("Payment successful for recharge record ID: " + rechargeRecord.);
//        } else {
//            // 在实际应用中，可能还需要记录支付失败的原因等信息
//            System.out.println("Payment failed for recharge record ID: " + rechargeRecord.getRecordId());
//        }
//
//        return paymentSuccess;
//    }

    // 获取支付方式列表
    @GetMapping("/payment-methods")
    public Result getPaymentMethods() {
        List<PaymentMethod> paymentMethods = paymentMethodService.list();
        return Result.ok().data("paymentMethods", paymentMethods);
    }

    @PostMapping("/choose-payment-method")
    public Result choosePaymentMethod(@RequestBody UserPaymentMethod userPaymentMethod) {
        // 根据实际情况进行逻辑处理，例如验证支付方式是否合法等
        // 这里假设 userPaymentMethod 包含了支付方式的相关信息
        userPaymentMethodService.save(userPaymentMethod);

        return Result.ok().message("Payment method chosen successfully");
    }
}
